package be.vdab.servlets;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.vdab.dao.PizzaDAO;
import be.vdab.entities.Pizza;

/**
 * Servlet implementation class PizzaToevoegenServlet
 */
@WebServlet("/pizzas/toevoegen.htm")
public class PizzaToevoegenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static final String VIEW = "/WEB-INF/JSP/pizzatoevoegen.jsp";
    private static final String REDIRECT_URL = "/menu/pizzas";
    private static final String SUCCES_VIEW = "/WEB-INF/JSP/pizzas.jsp";
    private final PizzaDAO pizzaDAO = new PizzaDAO();
    

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(VIEW).forward(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String,String> fouten = new HashMap<String,String>();
		String naam = request.getParameter("naam");
		if (naam == null || naam.isEmpty()){
			fouten.put("naam", "verplicht");
		}
		BigDecimal prijs = null;
		try{
			prijs = new BigDecimal(request.getParameter("prijs"));
			if(prijs.compareTo(BigDecimal.ZERO)<1){
				fouten.put("prijs", "tik een positief getal");
			}
		}catch (Exception ex){
			fouten.put("prijs", "tik een getal");
		}
		boolean pikant = "pikant".equals(request.getParameter("pikant"));
		if (fouten.isEmpty()){
			Pizza pizza = new Pizza(naam,prijs,pikant);
			pizzaDAO.create(pizza);
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + REDIRECT_URL));
			//request.setAttribute("pizzas", pizzaDAO.findAll());
			//request.getRequestDispatcher(SUCCES_VIEW).forward(request,  response);
		}else{
			request.setAttribute("fouten", fouten);
			request.getRequestDispatcher(VIEW).forward(request,  response);
		}
	}

}
